package com.fzkj.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @DESCRIPTION: TODO 接收浏览器请求
 * @AUTHOR: AnotherOne
 * @DATE: 2021/7/15 17:25
 */
public class HttpServer {
    /**
     * 1.创建socket对象，指定端口
     * 2.
     */

    public static void main(String[] args)   {
        // 创建socket
        ServerSocket serverSocket = null;
        Socket socket = null;
        BufferedReader reader = null;
        try {
            serverSocket = new ServerSocket(9999);
            System.out.println("服务已经启动~~");
            // 接受客户端的socket
            socket = serverSocket.accept();
            System.out.println("================");
            // 获得流对象
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            len = in.read(buf);
            String msg = new String(buf, 0, len);
            System.out.println(msg);
//            InetAddress address = serverSocket.getInetAddress();
//            String  ip = address.getHostAddress();
//            System.out.println(ip);
            String name = parseName(msg);
            OutputStream os = socket.getOutputStream();
            String html = "HTTP/1.1 200 ok\n\n\n hello " + name;
            os.write(html.getBytes());
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                if (reader != null){
                    reader.close();
                }
                if(socket != null){
                    socket.close();
                }
                if(serverSocket != null){
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 从请求的header中解析出来uri中携带的参数name
     * @param header
     * @return
     */
    protected static String parseName(String header){
        String name;
        int nameIndex = header.indexOf("name");
        int http = header.indexOf("HTTP");
        if (nameIndex == -1 || http == -1)
            name = "no param named name at all";
        else
            name = header.substring(nameIndex + 5, http);
        System.out.println("解析出来的name -> " + name);
        return name.trim();
    }
}
